package com.example.demo02.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo02.dao.TcPlatMapper;
import com.example.demo02.entity.TcPlat;
import com.example.demo02.exception.BusinessException;
import com.example.demo02.form.TcPlatForm;
import com.example.demo02.service.TcPlatService;
import com.github.pagehelper.PageHelper;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TcPlatServiceImpl extends ServiceImpl<TcPlatMapper, TcPlat> implements TcPlatService {
    @Resource
    TcPlatMapper tcPlatMapper;

    @Override
    public List<TcPlat> getTcPlatListByPage(TcPlatForm tcPlatForm) {
        PageHelper.startPage(tcPlatForm.getPageNum(), tcPlatForm.getLength());
        return tcPlatMapper.getTcPlatListByPage(tcPlatForm);
    }

    @Override
    @Transactional
    public void saveOrUpdateTcPlat(TcPlatForm tcPlatForm) {
        Assert.isTrue("1".equals(tcPlatForm.getActiontype()) || "2".equals(tcPlatForm.getActiontype()), () -> new BusinessException("不支持的操作类型"));
        Assert.isTrue(StrUtil.isNotBlank(tcPlatForm.getAccessName()), () -> new BusinessException("新增或修改,账号名称均不可为空"));
        if ("1".equals(tcPlatForm.getActiontype())) {
            Assert.isTrue(ObjectUtil.isNull(this.getOne(new QueryWrapper<TcPlat>().eq("access_name", tcPlatForm.getAccessName()))), () -> new BusinessException("新增失败,账号已存在,请重新输入"));
            TcPlat tcPlat = new TcPlat();
            BeanUtils.copyProperties(tcPlatForm, tcPlat);
            tcPlat.setCreateTime(new Date());
            this.save(tcPlat);
        } else if ("2".equals(tcPlatForm.getActiontype())) {
            Assert.isTrue(ObjectUtil.isNotNull(tcPlatForm.getPlatid()),()->new BusinessException("修改必须传入平台id"));
            Assert.isTrue(ObjectUtil.isNull(this.getOne(new QueryWrapper<TcPlat>().eq("access_name", tcPlatForm.getAccessName()).ne("platid",tcPlatForm.getPlatid()))), () -> new BusinessException("修改失败,账号已存在,请重新输入"));
            TcPlat tcPlat = new TcPlat();
            BeanUtils.copyProperties(tcPlatForm, tcPlat);
            tcPlat.setUpdateTime(new Date());
            String accessName = Opt.ofNullable(this.getById(tcPlatForm.getPlatid())).map(TcPlat::getAccessName).get();
            this.updateById(tcPlat);
        }
    }

}
